package com.example.feigner;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author cxx
 * @create 2020-01-18 0:12
 **/
@WebServlet(urlPatterns = "/gateway/*")
public class GatewayServlet extends HttpServlet {

    @Autowired
    private ILoadBalanceClientHttpRequestInterceptor iLoadBalanceClientHttpRequestInterceptor;

//    @Autowired
//    @ILoadBalanced
//    private RestTemplate restTemplate;

    @Autowired
    private GatewayConfiguration gatewayConfiguration;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String route = request.getPathInfo ().substring (1).split ("/")[0];
        String reRoute =  gatewayConfiguration.getRoute ().get (route);
        String uri = request.getPathInfo ().replaceFirst (route,reRoute).substring (1);
        RestTemplate restTemplate = new RestTemplate ();
        restTemplate.setInterceptors (Arrays.asList (iLoadBalanceClientHttpRequestInterceptor));
        String resp = restTemplate.getForObject ("http://"+uri,String.class);
        response.getWriter ().print (resp);
        response.getWriter ().flush ();
        response.getWriter ().close ();
    }
}
